package fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.hutoubenjg.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import activity.login.ActivityLogin;
import activity.luntan.TieZiMeActivity;
import activity.luntan.TieZiWriteActivity;
import activity.luntan.ToPicDetailActivity;
import adapter.LunTanPageIndexAdapter;
import base.BaseFragment;
import base.MyApplcation;
import bean.LuntanIndexPageBean;
import bean.SignInShowBean;
import bean.TopicListlBean;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import presenter.LunTanPresenter;
import util.utls.BasePtr;
import util.utls.ByAlert;
import util.utls.Const;
import util.utls.IsUtilUid;
import util.utls.SPUtils;
import util.volley.ResultEntity;
import widget.CarouselView;
import widget.LunBoUtils;


/**
 * 论坛
 */
public class LunTanFragment extends BaseFragment implements Observer, LunTanPageIndexAdapter.ClickListener {
    TextView tvTitle;
    ImageView back;
    ImageView img_other, img_other02;
    private LuntanIndexPageBean luntanbean;
    List<LuntanIndexPageBean.PostsTopEntity> topList;//置顶的数据
    CarouselView carouseView;//最上面的轮播
    LinearLayout list_head;
    ListView main_listview;
    View headerView;
    PtrFrameLayout commend_anchor_ptr;

    String uid;
    int size = 1;
    int page = 10;
    LunTanPresenter luntan;
    LunTanPageIndexAdapter xiaAdapter;
    TopicListlBean topicListlBean;
    List<TopicListlBean.TopicList> topicList;

    int zanPosition;//点赞的标记

    SignInShowBean signInShowBean;
    RelativeLayout qiandaoLIne;
    LinearLayout line;
    ImageView qiandaoIV;

    @Override
    public int initView() {
        return R.layout.fragment_luntan;
    }

    @Override
    public void onMyActivityCreated() {
        BasePtr.setPagedPtrStyle(commend_anchor_ptr);
        luntan = new LunTanPresenter(this);
        tvTitle.setText("论坛");
        back.setVisibility(View.GONE);
        img_other.setVisibility(View.VISIBLE);
        img_other02.setVisibility(View.VISIBLE);
        img_other.setImageResource(R.drawable.shuoshuo);
        img_other02.setImageResource(R.drawable.wode_tiezi);
        headerView = LayoutInflater.from(getActivity()).inflate(R.layout.luntanindexpage_headerview, null);
        carouseView = (CarouselView) headerView.findViewById(R.id.carouseView);
        list_head = (LinearLayout) headerView.findViewById(R.id.list_head);
        main_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), ToPicDetailActivity.class);
                intent.putExtra("id", topicList.get(position - 1).getId());
                startActivity(intent);
            }
        });
        luntanbean = new LuntanIndexPageBean();
        topicListlBean = new TopicListlBean();
        topicList = new ArrayList<>();
        topList = new ArrayList<>();
        uid =(String) SPUtils.get(MyApplcation.ctx, null, Const.ID, "");
        showProgressDialog("正在加载帖子数据...", true);
        if (!uid.equals("")){
            luntan.SignInShow(uid);
        }
        luntan.indexPage(6, uid);
        luntan.topicList(size, page, uid, "");

        xiaAdapter = new LunTanPageIndexAdapter(getActivity(), topicList, this);
        main_listview.setAdapter(xiaAdapter);
        main_listview.addHeaderView(headerView);
        commend_anchor_ptr.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                uid = (String) SPUtils.get(MyApplcation.ctx, null, Const.ID, "");
                size++;
                luntan.topicList(size, page, uid, "");
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                uid = (String) SPUtils.get(MyApplcation.ctx, null, Const.ID, "");
                luntan.topicList(size, page, uid, "");

                luntan.indexPage(6, uid);

            }
        });
        commend_anchor_ptr.autoRefresh(true);

        //登录的广播
        IntentFilter filter = new IntentFilter("chaingLogin");
        getActivity().registerReceiver(loginReceiver, filter);
    }

    BroadcastReceiver loginReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            uid = (String) SPUtils.get(MyApplcation.ctx, null, Const.ID, "");
            topList = new ArrayList<>();
            size = 1;
            luntan.indexPage(6, uid);
            luntan.topicList(size, page, uid, "");
            if (xiaAdapter != null) {
                xiaAdapter.notifyDataSetChanged();
            }
        }

        ;
    };
    @Override
    public void onResume() {
        super.onResume();
        uid = (String) SPUtils.get(MyApplcation.ctx, null, Const.ID, "");
        topList = new ArrayList<>();
        luntan.topicList(size, page, uid, "");
        luntan.indexPage(6, uid);
        if (xiaAdapter != null) {
            xiaAdapter.notifyDataSetChanged();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(loginReceiver);
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.img_other:
                uid = (String) SPUtils.get(getActivity(), null, Const.ID, "");
                if (uid.equals("")) {
                    startActivity(new Intent(getActivity(), ActivityLogin.class));
                    return;
                }
                intent = new Intent(getActivity(), TieZiWriteActivity.class);
                startActivity(intent);
                break;
            case R.id.img_other02:
                uid = (String) SPUtils.get(getActivity(), null, Const.ID, "");
                if (uid.equals("")) {
                    startActivity(new Intent(getActivity(), ActivityLogin.class));
                    return;
                }
                intent = new Intent(getActivity(), TieZiMeActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (!entity.getCode().equals("0")) {
                ByAlert.alert(entity.getMsg());
                return;
            }
            //帖子首页
            if (entity.getEventType() == LunTanPresenter.indexPage_success) {
                topList.clear();
                luntanbean = (LuntanIndexPageBean) entity.getData();
                if (luntanbean != null) {
                    new LunBoUtils().setLunBoData(getActivity(), luntanbean.getBanners(), carouseView);//轮播数据

                    topList.addAll(luntanbean.getPosts_top());
                    zhiDing(topList);//置顶
                    xiaAdapter.notifyDataSetChanged();
                }

            } else if (entity.getEventType() == LunTanPresenter.indexPage_fail) {
                ByAlert.alert(entity.getData());
            } else
                //帖子列表
                if (entity.getEventType() == LunTanPresenter.topicList_success) {
                    commend_anchor_ptr.refreshComplete();
                    if (size == 1) {
                        topicList.clear();
                    }
                    topicListlBean = (TopicListlBean) entity.getData();
                    if (topicListlBean != null) {
                        topicList.addAll(topicListlBean.getList());
                        xiaAdapter.notifyDataSetChanged();
                    }
                } else if (entity.getEventType() == LunTanPresenter.topicList_fail) {
                    ByAlert.alert(entity.getData());
                } else
                    //点赞
                    if (entity.getEventType() == LunTanPresenter.zan_success) {
                        ByAlert.alert(entity.getData());
                        luntan.topicList(size, page, uid, "");
                        topicList.get(zanPosition).setLikes(topicList.get(zanPosition).getLikes() + 1);
                        topicList.get(zanPosition).setHas_like(1);
                        xiaAdapter.notifyDataSetChanged();

                    } else if (entity.getEventType() == LunTanPresenter.zan_fail) {
                        ByAlert.alert(entity.getData());
                    }

            if (entity.getEventType() == LunTanPresenter.signin_success) {
                signInShowBean = new SignInShowBean();
                signInShowBean = (SignInShowBean) entity.getData();

                if ("0".equals(signInShowBean.getSign_today())) {
                    //当天未签到
                    luntan.SignIn(IsUtilUid.isUid());
                    qiandaoLIne.setVisibility(View.VISIBLE);
                    line.setEnabled(false);
                    qiandaoIV.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            qiandaoLIne.setVisibility(View.GONE);
                            line.setEnabled(true);
                        }
                    });

                } else if ("1".equals(signInShowBean.getSign_today())) {
                    //签过到


                }

            }
            if (entity.getEventType() == LunTanPresenter.signin_fail) {
            }

        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }

    /**
     * 置顶内容
     *
     * @param topList
     */
    private void zhiDing(List<LuntanIndexPageBean.PostsTopEntity> topList) {
        list_head.removeAllViews();
        for (int i = 0; i < topList.size(); i++) {
            RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 5, 0, 5);
            final View innerView = LayoutInflater.from(getActivity()).inflate(R.layout.item_luntan_head, null, false);
            final TextView head_tv = (TextView) innerView.findViewById(R.id.head_tv);
            head_tv.setText(topList.get(i).getUname() + ":" + topList.get(i).getTitle());
            innerView.setLayoutParams(params);
            list_head.addView(innerView);
            innerView.setTag(R.id.tag, topList.get(i).getId());
            innerView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ToPicDetailActivity.class);
                    intent.putExtra("id", Integer.parseInt(innerView.getTag(R.id.tag).toString()));
                    startActivity(intent);
                }
            });
        }
    }

    //点赞
    @Override
    public void dianzan(View v) {
        zanPosition = (Integer) v.getTag();
        if (IsUtilUid.isUid() == null || IsUtilUid.isUid() == "") {
            Intent intent1 = new Intent(getActivity(), ActivityLogin.class);
            getActivity().startActivity(intent1);
        } else {
            luntan.dianzan(uid, topicList.get(zanPosition).getId() + "", "");
        }
    }

    //评论
    @Override
    public void pinglun(View v) {
        int s = (Integer) v.getTag();

    }
}
